// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';

// This method is called when your extension is activated
// Your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {

	// Use the console to output diagnostic information (console.log) and errors (console.error)
	// This line of code will only be executed once when your extension is activated
	console.log('Congratulations, your extension "bumpycode" is now active!');

	// The command has been defined in the package.json file
	// Now provide the implementation of the command with registerCommand
	// The commandId parameter must match the command field in package.json
	const disposable = vscode.commands.registerCommand('bumpycode.helloWorld', () => {
		// The code you place here will be executed every time your command is executed
		const editor = vscode.window.activeTextEditor;
		if (!editor) {
			vscode.window.showInformationMessage('没有活动的编辑器');
			return; // No open text editor
		}
		// 获取当前文档的 URI
		const documentUri = editor.document.uri;
		// 获取当前文档的文件路径
		const filePath = documentUri.fsPath;
		// 获取当前文档的全部文本内容
		const filecontent = editor.document.getText();
		// Display a message box to the user
		vscode.window.showInformationMessage(`文件路径: ${filePath}, 文本长度: ${filecontent.length}`);
		// 获取当前选中的文本
		const selection = editor.selection;
		const selectedText = editor.document.getText(selection);
		// 从配置中获取要替换的文本和替换为的文本, 默认为 "bumpy" 和 "bump".
		// 配置信息存放在 package.json 文件中了
		const config = vscode.workspace.getConfiguration('bumpycode');
		const textToReplace = config.get('textToReplace', 'bumpy');
		const replacementText = config.get('replacementText', 'bump');


		// 判断是否选中了文本
		if(selectedText) {
			// 显示选中的文本
			vscode.window.showInformationMessage(`选中的文本：${selectedText}`);
			// 替换选中的文本
			// 使用正则表达式动态创建替换模式
			const replaceRegex = new RegExp(textToReplace, 'g');
			const newText = selectedText.replace(replaceRegex, replacementText);
			// 计算替换次数
			const replacementCount = (selectedText.match(replaceRegex) || []).length;
			if (replacementCount === 0) {
				vscode.window.showInformationMessage('选中的文本中没有找到"bumpy"。');
				return;
			}
			editor.edit(editBuilder => {
				editBuilder.replace(selection, newText);
			}).then(success => {
				if(success) {
					vscode.window.showInformationMessage(`替换成功 ${replacementCount} 次`);
				} else {
					vscode.window.showInformationMessage(`替换失败`);
				}
			});
		}
	});

	context.subscriptions.push(disposable);
}

// This method is called when your extension is deactivated
export function deactivate() {}
